package com.talking.activities.main
import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.google.gson.Gson
import com.google.gson.JsonParser
import com.talking.App
import com.talking.R
import com.talking.bean.UserBean
import com.talking.databinding.ActivityMainBinding
import com.talking.util.Network
import com.talking.util.Tools
import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import java.io.IOException

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private val calls: MutableList<Call> = ArrayList()
    @RequiresApi(Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        supportActionBar!!.hide()
        val navController = findNavController(R.id.nav_host_fragment_activity_main)
        setupActionBarWithNavController(navController, AppBarConfiguration(setOf(R.id.navigation_message, R.id.navigation_friend, R.id.navigation_me)))
        binding.navView.setupWithNavController(navController)
        Tools.requestPermission(this)
        refresh(null)
    }
    fun refresh(callback:RefreshCallback?) {
        val map = HashMap<String, String>()
        map["mail"]= App.sp.getString("mail","").toString()
        Network.post(map, "user/getuserbymail/") { call: Call ->
            call.enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) { e.printStackTrace() }
                override fun onResponse(call: Call, response: Response) {
                    runOnUiThread{
                        val jo = JsonParser.parseString(response.body!!.string()).asJsonObject
                        val msg = jo.get("msg").asString
                        if (msg.equals("获取成功")){
                            App.me= Gson().fromJson(jo.get("data").asJsonObject, UserBean::class.java)
                            callback?.callback()
                        }else{
                            Tools.toast(msg)
                        }
                    }
                }
            })
            calls.add(call)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        for(c in calls)c.cancel()
    }
}